﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CRMAdminDashboard.CrmSvc;
using CRMAdminDashboard.Properties;
using System.Collections;

namespace CRMAdminDashboard
{
    public partial class FormManageViews : Form, IUtilityForm
    {

        #region Constants

        private const string SETTING_QUERYTYPES = "QueryTypes";
        private const string RES_VIEWSFORM_FORMHELP = "RES_VIEWSFORM_FORMHELP";
        private const string RES_VIEWSFORM_CLONEVIEW = "RES_VIEWSFORM_CLONEVIEW";
        private const string RES_VIEWSFORM_COMPARE = "RES_VIEWSFORM_COMPARE";
        private const string RES_VIEWSFORM_ACTIVATE = "RES_VIEWSFORM_ACTIVATE";
        private const string RES_VIEWSFORM_DEACTIVATE = "RES_VIEWSFORM_DEACTIVATE";
        private const string RES_VIEWSFORM_DELETE = "RES_VIEWSFORM_DELETE";

        #endregion

        #region Fields

        /// <summary>
        /// Static pointer to my console
        /// </summary>
        private static TextBox _logWindow;

        /// <summary>
        /// True when the parent form has ordered to close
        /// </summary>
        private bool _closeFromParent;

        /// <summary>
        /// Code behind
        /// </summary>
        private HelperManageViews _helper;

        #endregion

        #region Properties

        /// <summary>
        /// A combination of the selected query types. Note that in _selectedQueryTypes "MainApplicationView"
        /// is represented by 4096 instead than 0. This property lives in the helper.
        /// </summary>
        public uint SelectedQueryTypes
        {
            get
            {
                return this._helper.SelectedQueryTypes;
            }
            set
            {
                this._helper.SelectedQueryTypes = value;
            }
        }

        #endregion

        #region Entry Points

        /// <summary>
        /// Standard constructor
        /// </summary>
        public FormManageViews(CachingCrmService svcHandle)
        {
            InitializeComponent();
            this._helper = new HelperManageViews(svcHandle);
            EnableControls();
            cbShowType.SelectedIndex = 0;
            cbOnExisting.SelectedIndex = 0;
            cbViewFormat.SelectedIndex = 0;
            HelperManageViews.QueryPrintFormat = cbViewFormat.SelectedIndex;
            _logWindow = txtOutput;
        }

        /// <summary>
        /// Called by the Parent form when logging out. Will force this form shut.
        /// </summary>
        public void ParentClose()
        {
            this._closeFromParent = true;
            this.Close();
            this._closeFromParent = false;
        }

        /// <summary>
        /// Write on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(bool logInMain, string msg)
        {
            _logWindow.AppendText(msg);
            if (logInMain)
            {
                FormLogin.WriteLog(msg);
            }
        }

        /// <summary>
        /// Write an exception on the console
        /// </summary>
        /// <param name="logInMain">Write also on the parent's console</param>
        public static void WriteLog(bool logInMain, Exception ex)
        {
            ClearLog();
            WriteLog(logInMain, FormLogin.FormatException(ex) + Environment.NewLine + Environment.NewLine);
        }

        /// <summary>
        /// Clear the console
        /// </summary>
        public static void ClearLog()
        {
            _logWindow.Clear();
        }

        #endregion

        #region Events

        private void FormManageViews_Load(object sender, EventArgs e)
        {
            lblHelpForm.Text = Program.GetResString(RES_VIEWSFORM_FORMHELP);
            btnCloneView.Text = Program.GetResString(RES_VIEWSFORM_CLONEVIEW);
            btnCompareUsers.Text = Program.GetResString(RES_VIEWSFORM_COMPARE);
            btnActivate.Text = Program.GetResString(RES_VIEWSFORM_ACTIVATE);
            btnDeactivate.Text = Program.GetResString(RES_VIEWSFORM_DEACTIVATE);
            btnDelete.Text = Program.GetResString(RES_VIEWSFORM_DELETE);

            this.SelectedQueryTypes = (uint)Settings.Default[SETTING_QUERYTYPES];
            SavedQueryType.LoadList(chkQueryType, this.SelectedQueryTypes);
            chkQueryType.ItemCheck += new ItemCheckEventHandler(chkQueryType_ItemCheck);
        }

        private void FormManageViews_FormClosed(object sender, FormClosedEventArgs e)
        {
            Settings.Default[SETTING_QUERYTYPES] = this.SelectedQueryTypes;

            if (!this._closeFromParent)
            {
                ((FormLogin)this.Owner).ForceLogout();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lstFromUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this._helper.GetViews((SystemUser)lstFromUser.SelectedItem, lstViews, true);
            }
            finally
            {
                this.EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void lstViews_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selected = lstViews.SelectedItems.Count;
            if (selected == 0)
            {
                lblViewsSelected.Text = null;
            }
            else
            {
                lblViewsSelected.Text = selected.ToString() + " selected";
            }
            this.EnableControls();
        }

        private void lstToUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selected = lstToUsers.SelectedItems.Count;
            if (selected == 0)
            {
                lblToUsersSelected.Text = null;
            }
            else
            {
                lblToUsersSelected.Text = selected.ToString() + " selected";
            }
            this.EnableControls();
        }

        private void btnGetUsers_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnGetUsers.Enabled = false;
                this._helper.GetUsers(lstFromUser, lstToUsers);
                if (this._helper.BuFilter != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Warning! BU Filter ON (");
                    foreach (BusinessUnit bu in this._helper.BuFilter.Values)
                    {
                        sb.Append(bu.Name + ", ");
                    }
                    sb.Length = sb.Length - 2;
                    sb.Append(")");
                    lblWarning.Text = sb.ToString();
                }
                else
                {
                    lblWarning.Text = null;
                }
            }
            finally
            {
                btnGetUsers.Enabled = true;
                this.EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void chkQueryType_ClientSizeChanged(object sender, EventArgs e)
        {
            chkQueryType.ColumnWidth = (int)(0.5 + chkQueryType.ClientSize.Width / 3.1);
        }

        private void chkQueryType_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            this.SelectedQueryTypes = SavedQueryType.CheckStatusChanged(this.SelectedQueryTypes,
                (SavedQueryType)chkQueryType.Items[e.Index], e.NewValue);
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this._helper.GetViews((SystemUser)lstFromUser.SelectedItem, lstViews, false);
            }
            finally
            {
                this.EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void lstViews_DoubleClick(object sender, EventArgs e)
        {
            btnShowQuery_Click(sender, e);
        }

        private void btnShowQuery_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnShowQuery.Enabled = false;
                IEnumerable<UserQuery> views = lstViews.SelectedItems.Cast<UserQuery>();
                SystemUser su = (SystemUser)lstFromUser.SelectedItem;
                this._helper.ShowView(views, su.Id, cbShowType.SelectedIndex);
            }
            finally
            {
                btnShowQuery.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnCloneView_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnCloneView.Enabled = false;
                this._helper.CloneViews(
                    (SystemUser)lstFromUser.SelectedItem,
                    new ArrayList(lstViews.SelectedItems).Cast<UserQuery>(),
                    new ArrayList(lstToUsers.SelectedItems).Cast<SystemUser>(),
                    cbOnExisting.SelectedIndex);
            }
            finally
            {
                btnCloneView.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void cbViewFormat_SelectedIndexChanged(object sender, EventArgs e)
        {
            HelperManageViews.QueryPrintFormat = cbViewFormat.SelectedIndex;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this._helper.GetViews((SystemUser)lstFromUser.SelectedItem, lstViews, false);
            }
            finally
            {
                this.EnableControls();
                this.Cursor = Cursors.Default;
            }
        }

        private void btnCompareUsers_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnCompareUsers.Enabled = false;
                this._helper.CompareUsers((SystemUser)lstFromUser.SelectedItem,
                    new ArrayList(lstToUsers.SelectedItems).Cast<SystemUser>());
            }
            finally
            {
                btnCompareUsers.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnActivate_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnActivate.Enabled = false;
                if (this._helper.ActivateViewsForUsers(new ArrayList(lstViews.SelectedItems).Cast<UserQuery>(),
                    new ArrayList(lstToUsers.SelectedItems).Cast<SystemUser>(), true))
                {
                    lstFromUser_SelectedIndexChanged(null, null);
                }
            }
            finally
            {
                btnActivate.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnDeactivate_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnDeactivate.Enabled = false;
                if (this._helper.ActivateViewsForUsers(new ArrayList(lstViews.SelectedItems).Cast<UserQuery>(),
                    new ArrayList(lstToUsers.SelectedItems).Cast<SystemUser>(), false))
                {
                    lstFromUser_SelectedIndexChanged(null, null);
                }
            }
            finally
            {
                btnDeactivate.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                btnDelete.Enabled = false;
                MessageBox.Show("Not yet implemented. This is a dangerous action. If you REALLY think that you need it let me know and I'll make this available.");
            }
            finally
            {
                btnDelete.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void activateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this._helper.ActivateViews((SystemUser)lstFromUser.SelectedItem,
                    new ArrayList(lstViews.SelectedItems).Cast<UserQuery>(),
                    true))
                {
                    lstFromUser_SelectedIndexChanged(null, null);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void deactivateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this._helper.ActivateViews((SystemUser)lstFromUser.SelectedItem,
                    new ArrayList(lstViews.SelectedItems).Cast<UserQuery>(),
                    false))
                {
                    lstFromUser_SelectedIndexChanged(null, null);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this._helper.DeleteViews((SystemUser)lstFromUser.SelectedItem,
                    new ArrayList(lstViews.SelectedItems).Cast<UserQuery>()))
                {
                    lstFromUser_SelectedIndexChanged(null, null);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void renameViewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (this._helper.RenameView((SystemUser)lstFromUser.SelectedItem, (UserQuery)lstViews.SelectedItem))
                {
                    lstFromUser_SelectedIndexChanged(null, null);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void mnuLstViews_Opening(object sender, CancelEventArgs e)
        {
            bool active;
            bool inactive;
            int numSelected;
            GetViewSelectionInfo(out active, out inactive, out numSelected);

            deactivateToolStripMenuItem.Enabled = active;
            activateToolStripMenuItem.Enabled = inactive;
            deleteToolStripMenuItem.Enabled = (numSelected >= 1);
            renameViewToolStripMenuItem.Enabled = (numSelected == 1);
        }

        #endregion

        #region Local Methods

        /// <summary>
        /// Enable/disable controls accordingly
        /// </summary>
        private void EnableControls()
        {
            if (lstFromUser.Items.Count > 0)
            {
                lblHelpForm.Visible = true;
                lblFromUser.Enabled = true;
                lstFromUser.Enabled = true;
                if (lstViews.Items.Count > 0)
                {
                    cbViewFormat.Visible = true;
                    lstViews.Enabled = true;
                    lblViewsSelected.Visible = true;
                    if (lstToUsers.Items.Count > 0)
                    {
                        lblToUsers.Enabled = true;
                        lstToUsers.Enabled = true;
                        lblToUsersSelected.Visible = true;
                    }
                    else
                    {
                        lblToUsers.Enabled = false;
                        lstToUsers.Enabled = false;
                        lblToUsersSelected.Visible = false;
                    }
                }
                else
                {
                    cbViewFormat.Visible = false;
                    lstViews.Enabled = false;
                    lblViewsSelected.Visible = false;
                }

                if (lstViews.SelectedItems.Count > 0)
                {
                    btnShowQuery.Visible = true;
                    cbShowType.Visible = true;
                    if (lstToUsers.SelectedItems.Count > 0)
                    {
                        btnCloneView.Visible = true;
                        lblOnExisting.Visible = true;
                        cbOnExisting.Visible = true;
                    }
                    else
                    {
                        btnCloneView.Visible = false;
                        lblOnExisting.Visible = false;
                        cbOnExisting.Visible = false;
                    }
                }
                else
                {
                    btnShowQuery.Visible = false;
                    cbShowType.Visible = false;
                    btnCloneView.Visible = false;
                    lblOnExisting.Visible = false;
                    cbOnExisting.Visible = false;
                }
            }
            else
            {
                lblHelpForm.Visible = false;
                lblFromUser.Enabled = false;
                lstFromUser.Enabled = false;
                cbViewFormat.Visible = false;
                lstViews.Enabled = false;
                lblViewsSelected.Visible = false;
                lblToUsers.Enabled = false;
                lstToUsers.Enabled = false;
                lblToUsersSelected.Visible = false;
                btnShowQuery.Visible = false;
                cbShowType.Visible = false;
                btnCloneView.Visible = false;
                lblOnExisting.Visible = false;
                cbOnExisting.Visible = false;
            }

            if (lstFromUser.SelectedItems.Count > 0 && lstToUsers.SelectedItems.Count > 0)
            {
                btnCompareUsers.Visible = true;
            }
            else
            {
                btnCompareUsers.Visible = false;
            }

            if (lstViews.SelectedItems.Count > 0 && lstToUsers.SelectedItems.Count > 0)
            {
                btnActivate.Visible = true;
                btnDeactivate.Visible = true;
                btnDelete.Visible = true;
            }
            else
            {
                btnActivate.Visible = false;
                btnDeactivate.Visible = false;
                btnDelete.Visible = false;
            }
        }

        /// <summary>
        /// Decide if there are selected views active, inactive and how many selected views there are
        /// </summary>
        private void GetViewSelectionInfo(out bool active, out bool inactive, out int numSelected)
        {
            active = false;
            inactive = false;
            numSelected = 0;
            foreach (UserQuery view in lstViews.SelectedItems.Cast<UserQuery>())
            {
                numSelected++;
                if (view.StateCode == UserQueryState.Active)
                {
                    active = true;
                }
                else
                {
                    inactive = true;
                }
            }
        }

        #endregion

    }
}
